#include "Texture.h"
#include "GLAllInOne.h"
#include <iostream>

#ifndef STB_IMAGE_IMPLEMENTATION
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#endif

namespace ManchyGL
{
	Texture::Texture()
	{}
	Texture::~Texture()
	{}
	void Texture::Load(char const *filename)
	{
		unsigned int texture;
		// texture 1
		// ---------
		glGenTextures(1, &texture);
		//glActiveTexture(GL_TEXTURE0);
		glBindTexture(GL_TEXTURE_2D, texture);

		// set the texture wrapping parameters
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // GL_CLAMP_TO_BORDER  GL_CLAMP_TO_EDGE GL_REPEAT GL_MIRRORED_REPEAT
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
		// set texture filtering parameters
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);    // GL_POINT  GL_LINEAR
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		// load image, create texture and generate mipmaps
		int width, height, nrChannels;
		stbi_set_flip_vertically_on_load(true); // tell stb_image.h to flip loaded texture's on the y-axis.
		// The FileSystem::getPath(...) is part of the GitHub repository so we can find files on any IDE/platform; replace it with your own image path.

		unsigned char *data = stbi_load(filename, &width, &height, &nrChannels, 0);
		if (data)
		{
			glTexImage2D(GL_TEXTURE_2D, 0, (nrChannels == 4) ? GL_RGBA : GL_RGB, width, height, 0, (nrChannels == 4) ? GL_RGBA : GL_RGB, GL_UNSIGNED_BYTE, data);
			glGenerateMipmap(GL_TEXTURE_2D);
			_isValid = true;
		}
		else
		{
			_isValid = false;
			std::cout << "Failed to load texture" << std::endl;
		}
		stbi_image_free(data);

		_texId = texture;
		_width = width;
		_height = height;
		_channels = nrChannels;
	}

	bool Texture::IsValid()
	{
		return _isValid;
	}

	bool Texture::GetTextureId()
	{
		return _texId;
	}
}
